<!-- 功能搜索 -->
<template>
  <div class="power-search">
    <el-autocomplete v-model="state" :fetch-suggestions="querySearchAsync" placeholder="请输入菜单名称" clearable
      @select="handleSelect">
      <template #suffix>
        <el-icon @click="search(state)">
          <Promotion />
        </el-icon>
      </template>
      <!-- <i slot="suffix" class="icon el-input__icon el-icon-s-promotion" style="font-weight: 900; cursor: pointer"
        @click="search(state)"></i> -->
    </el-autocomplete>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'powerSearch',
  components: {},
  data() {
    return {
      restaurants: [],
      state: '',
      timeout: null,
    }
  },
  computed: {
    ...mapState(['powerMenu']),
  },
  watch: {
    // 监听 powerMenu 的变化
    powerMenu(newVal) {
      // 当数据发生变化时执行的操作
      this.restaurants = this.flattenArray(this.powerMenu)
    },
  },
  methods: {
    ...mapActions(['getParentMenu']),
    flattenArray(arr) {
      return arr.reduce((acc, item) => {
        if (item.children) {
          return acc.concat(this.flattenArray(item.children))
        } else {
          return acc.concat({ value: item.name, name: item.name, id: item.id, href: item.href })
        }
      }, [])
    },
    search(state) {
      const href = this.restaurants.filter((item) => item.value == state)
      this.handleSelect(href[0])
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants

      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 1000 * Math.random())
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1
      }
    },
    handleSelect(item) {
      //
      this.getParentMenu(item)
      localStorage.setItem('menuId', this.getParentMenu())

      this.$router.push({ path: item.href })
      this.$store.commit('Tage', item.href)
      this.$store.commit('getvisited', item)
    },
  },
}
</script>
<style lang="less" scoped>
.power-search {
  margin: 10px auto;
  width: 180px;
  // margin: 0 13px;
}

.el-input__inner {
  // background: transparent !important;
  border: none;
  // border-radius: 0px;
  // color: #409eff;
}

.el-input__suffix {
  color: #409eff;
}

// /* 修改placeholder的颜色 */
//  .el-input__inner::-webkit-input-placeholder {
//   color: #fff; /* 更改为你想要的颜色 */
// }
//  .el-input__inner:-moz-placeholder {
//   color: #fff; /* 兼容Firefox 4-18 */
// }
//  .el-input__inner::-moz-placeholder {
//   color: #fff; /* 兼容Firefox 19+ */
// }
//  .el-input__inner:-ms-input-placeholder {
//   color: #fff; /* 兼容IE 10+ */
// }</style>
